//
//  LastTenTableViewController.swift
//  ReadingNow
//
//  Created by iOS Developer on 2017/6/19.
//  Copyright © 2017年 lig. All rights reserved.
//

import UIKit
import Alamofire
import Kanna
class LastTenTableViewController: UITableViewController {
    
    var tenChapters = [(String,String)]()
    var allChapters = ""
    var shouldBeRed: Int?
    @IBAction func LoadAllChapters(_ sender: UIBarButtonItem) {
        title = "加载中..."
        
        Alamofire.request(allChapters).responseData {[weak self] resp in
            if let data = resp.result.value {
                if let doc = HTML(html: data, encoding: .utf8), let dhost = resp.response?.url?.host  {
                    var _tenChapters = [(String,String)]()
                    var chapterName: String?
                    if dhost == "m.qu.la"{
                        for chapter in doc.xpath("//div[@id='chapterlist']//a") {
                            _tenChapters.append((chapter.text!,"http://m.qu.la/" + chapter["href"]!))
                        }
                        _tenChapters.remove(at: 0)
                        chapterName = doc.xpath("//span[@class='title']").first?.text
                    }else if dhost == "m.biqudu.com" {
                        for chapter in doc.xpath("//ul[@class='chapter']//a") {
                            _tenChapters.append((chapter.text!,"http://m.biqudu.com/" + chapter["href"]!))
                        }
                        chapterName = doc.xpath("//h1[@id='bqgmb_h1']").first?.text
                    }
                    var latestIndex: Int?
                    if let cpn = chapterName, let latestedRead = UserDefaults.standard.value(forKey: cpn) as? String{
                        for (index,value) in _tenChapters.enumerated() {
                            if value.1.contains(latestedRead) {
                                latestIndex = index
                                break
                            }
                        }
                    }
                    DispatchQueue.main.async {
                        self?.tenChapters = _tenChapters
                        self?.tableView.reloadData()
                        self?.title = chapterName ?? "完整目录"
                        if let latestIndex = latestIndex {
                            let indexPath = IndexPath(row: latestIndex, section: 0)
                            self?.tableView.scrollToRow(at: indexPath, at: .top, animated: true)
                            self?.shouldBeRed = latestIndex
                            self?.tableView.reloadRows(at: [indexPath], with: .automatic)
                        }
                        
                    }
                }
            }else {
                DispatchQueue.main.async {
                    let alert = UIAlertController(title: "提示", message: resp.result.error?.localizedDescription, preferredStyle: .alert)
                    alert.addAction(UIAlertAction(title: "确定", style: .default))
                    self?.present(alert, animated: true)
                }
            }
        }
        
    }
    
    
    // MARK: - Table view data source
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return tenChapters.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "title cell", for: indexPath)
        cell.textLabel?.text = tenChapters[indexPath.row].0
        if shouldBeRed == indexPath.row {
            cell.textLabel?.textColor = .red
        }else {
            cell.textLabel?.textColor = .black
        }
        return cell
    }
    
    // MARK: - Navigation
    
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "loadContent", let dest = segue.destination as? ContentViewController {
            let indexPath = tableView.indexPathForSelectedRow!
            dest.contentURL = tenChapters[indexPath.row].1
        }
    }
}
